import org.devops.JavaApplicationTemplate
def call(Map map) {
    pipeline {
        agent any

        environment {

            BASE_IMAGE = "${map.BASE_IMAGE? map.BASE_IMAGE : 'openjdk:21-jdk-slim'}"

            GIT_BRANCH = "${map.GIT_BRANCH ?: 'master'}"
            HARBOR_REGISTRY_URL = "${map.HARBOR_REGISTRY_URL ?: 'harbor.zuolang.cn'}"
            HARBOR_PROJECT_NAME = "${map.HARBOR_PROJECT_NAME ?: 'java'}"
            RESOURCE_LIMITS_CPU = "${map.CPU ?: '100m'}"
            RESOURCE_LIMITS_MEM = "${map.MEMORY ?: '512Mi'}"
            RESOURCE_REQUESTS_MEM = "${map.CPU ?: '512Mi'}"
            RESOURCE_REQUESTS_CPU = "${map.MEMORY ?: '100m'}"
            DEPLOY_REPLICAS = "${map.REPLICAS?: '1'}"
            TIMESTAMP = new Date().format("yyyyMMdd_HHmm")
        }

        options {
            timeout(time: 1, unit: 'HOURS')
            timestamps()
        }

        parameters {
            string(name: 'GIT_BRANCH', defaultValue: map.BRANCH, description: '请选择发布分支')
            choice(name: 'REMOTE_HOST', choices: map.HOSTS, description: '选择要发布的主机,默认为ALL') // 定义项目对应的主机列表
            choice(name: 'MODE', choices: ['DEPLOY','ROLLBACK'], description: '请选择发布或者回滚？')
            choice(name: 'GIT_AUTH', choices: ['gitee'], description: '请选择代码仓库凭据')
            choice(name: 'HARBOR_AUTH', choices: ['harbor'], description: '请选择产品镜像仓库凭据')
            booleanParam description: '重新部署：删除重建或者只更新镜像', name: 'REDEPLOY', defaultValue: false
            booleanParam description: '跳过单元测试：', name: 'SKIP_TEST', defaultValue: true
            choice(name: 'NAMESPACE', choices: ['default'], description: '请选择namespace')
        }

        stages {
            stage('数据检查') {
                steps {
                    script {
                        JavaApplicationTemplate.preCheck(map)
                    } 
                }                
            }

            stage('代码拉取') {
                steps {
                    script {
                       def branch = params.BRANCH? params.BRANCH : env.GIT_BRANCH
                       checkout scmGit(
                        branches: [[name: branch]], 
                        extensions: [], 
                        userRemoteConfigs: [[credentialsId: 'gitee', url: map.GIT_URL]]) 
                    } 
                } 
            } 

            stage('单元测试') {
                when {
                    expression { params.SKIP_TEST != true }
                }
                
                steps {
                    script {
                        configFileProvider([configFile(fileId: 'maven_global_settings',targetLocation: "settings.xml", variable: 'settingsXml')]) {
                            sh "mvn test -DfailIfNoTests=false -s settings.xml"
                        }                      
                    }
                }
            }

            stage('代码打包') {
                steps {
                    script{
                        withCredentials([usernamePassword(credentialsId: params.HARBOR_AUTH,usernameVariable: 'HARBOR_USERNAME',passwordVariable: 'HARBOR_PASSWORD')]) {
                            def TAG = "${env.TIMESTAMP}_${env.BUILD_NUMBER}"
                            def settingsXml = "settings.xml"
                            configFileProvider([configFile(fileId: 'maven_global_settings',targetLocation: settingsXml, variable: 'settingsXml')]) {}

                            def fromImage = "${env.HARBOR_REGISTRY_URL}/${map.BASE_IMAGE}"
                            def toImage = "${env.HARBOR_REGISTRY_URL}/${env.HARBOR_PROJECT_NAME}/${map.SERVICE_NAME}:${TAG}"

                            def buildCmd = ""
                            if (map.MODULE_NAME) {
                                buildCmd  = "mvn clean package -pl ${map.MODULE_NAME} -am -Dmaven.test.skip=true -DskipDocs com.google.cloud.tools:jib-maven-plugin:3.4.4:build \\"
                            }else{
                                buildCmd  = "mvn clean package -Dmaven.test.skip=true -DskipDocs com.google.cloud.tools:jib-maven-plugin:3.4.4:build \\"
                            }
                             
                            buildCmd += """
                                -s settings.xml \
                                -Djib.from.platforms=linux/amd64 \
                                -Djib.platforms=linux/amd64 \
                                -Djib.from.image=${fromImage} \
                                -Djib.from.auth.username=${HARBOR_USERNAME} \
                                -Djib.from.auth.password=${HARBOR_PASSWORD} \
                                -Djib.to.image=${toImage} \
                                -Djib.to.auth.username=${HARBOR_USERNAME} \
                                -Djib.to.auth.password=${HARBOR_PASSWORD} \
                                -Djib.allowInsecureRegistries=true \
                            """

                            buildCmd += "-Djib.container.environment='JAVA_TOOL_OPTIONS=-XX:ErrorFile=./jvm_error.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heapdump.hprof -Xloggc:./gc.log' "

                            if (map.MAIN_CLASS != null && map.MAIN_CLASS.length() > 0) {
                                buildCmd += " -Djib.container.mainClass=${map.MAIN_CLASS}"
                            }
                            sh "${buildCmd}"
                        }
                    }
                } 
            }

            stage('helm部署k8s') {
                when {
                    expression { params.MODE == 'DEPLOY' }
                }
                steps {
                    script {
                        sh """
                        if [ -d "./charts" ]; then
                            echo "目录 charts 已存在，跳过创建。"
                        else
                            mkdir charts
                        fi

                        if [ -d "./charts/${map.SERVICE_NAME}" ]; then
                            echo "目录 charts 已存在，跳过创建。"
                        else
                            helm create ./charts/${map.SERVICE_NAME}
                        fi
                       """
                        sh """
                        helm upgrade --install ${map.SERVICE_NAME} ./charts/${map.SERVICE_NAME} \
                        --version 1.0.0 \
                        --set imageRepository=${env.HARBOR_REGISTRY_URL}/${env.HARBOR_PROJECT_NAME}/${map.SERVICE_NAME} \
                        --set appVersion=${map.APP_VERSION} \
                        --set imageTag=${env.TIMESTAMP}_${env.BUILD_NUMBER} \
                        --set imagePullPolicy=Always \
                        --set replicaCount=${env.DEPLOY_REPLICAS} \
                        --set resources.limits.cpu=${env.RESOURCE_LIMITS_CPU} \
                        --set resources.limits.memory=${env.RESOURCE_LIMITS_MEM} \
                        --set resources.requests.cpu=${env.RESOURCE_REQUESTS_CPU} \
                        --set resources.requests.memory=${env.RESOURCE_REQUESTS_MEM} \
                        --set service.port=${map.PORT} \
                        --namespace=${params.NAMESPACE}
                        """
                    }
                }
            }
        }
    }
}
